<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 */

namespace app\api\controller;

use app\model\community\CommunityAccount;
use app\model\community\Config as CommunityConfig;
use app\model\community\CommunityLevel;
use app\model\community\Leader;
use app\model\member\Member as MemberModel;
use app\model\order\Order;
use app\model\community\Poster;

/**
 * 团长管理
 * @author Administrator
 *
 */
class Community extends BaseApi
{

    /**
     * 团长申请
     */
    public function apply()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $leader_model = new Leader();
        $leader_info = $leader_model->getLeaderInfo([ 'member_id' => $token[ 'data' ][ 'member_id' ] ], '*');
        if (!empty($leader_info[ 'data' ])) {
            if ($leader_info[ 'data' ][ 'status' ] == 0) {
                return $this->response($this->error("", "当前有正在审核中的信息不可重复提交!"));
            } elseif ($leader_info[ 'data' ][ 'status' ] == 1 || $leader_info[ 'data' ][ 'status' ] == 3) {
                return $this->response($this->error("", "您已经是社区团长!"));
            }
        }

        $data = array (
            'member_id' => $this->member_id,
            'site_id' => $this->site_id,
            'name' => isset($this->params[ 'name' ]) ? $this->params[ 'name' ] : '',
            'mobile' => isset($this->params[ 'mobile' ]) ? $this->params[ 'mobile' ] : '',
            'community' => isset($this->params[ 'community' ]) ? $this->params[ 'community' ] : '',
            'community_img' => isset($this->params[ 'community_img' ]) ? $this->params[ 'community_img' ] : '',
            'wechat' => isset($this->params[ 'wechat' ]) ? $this->params[ 'wechat' ] : '',
            'province_id' => isset($this->params[ 'province_id' ]) ? $this->params[ 'province_id' ] : '',
            'city_id' => isset($this->params[ 'city_id' ]) ? $this->params[ 'city_id' ] : '',
            'district_id' => isset($this->params[ 'district_id' ]) ? $this->params[ 'district_id' ] : '',
            'address' => isset($this->params[ 'address' ]) ? $this->params[ 'address' ] : '',
            'full_address' => isset($this->params[ 'full_address' ]) ? $this->params[ 'full_address' ] : '',
            'longitude' => isset($this->params[ 'longitude' ]) ? $this->params[ 'longitude' ] : '',
            'latitude' => isset($this->params[ 'latitude' ]) ? $this->params[ 'latitude' ] : '',
        );

        $leader_model = new Leader();
        $res = $leader_model->applyLeader($data);
        return $this->response($res);
    }

    /**
     * 团长等级
     */
    public function levelList()
    {
        $level_model = new CommunityLevel();
        $list = $level_model->getCommunityLevelList([ 'site_id' => $this->site_id ]);
        return $this->response($list);
    }

    /**
     * 团长信息
     */
    public function getLeaderInfo()
    {

        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $leader_model = new Leader();
        $info = $leader_model->getLeaderInfo([ [ 'member_id', '=', $this->member_id ] ]);
        return $this->response($info);
    }

    /**
     * 团长详细信息
     */
    public function getLeaderDetail()
    {

        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);
        $leader_model = new Leader();
        $info = $leader_model->getLeaderInfo([ [ 'member_id', '=', $this->member_id ] ]);
        if (empty($info[ 'data' ])) return $this->response($this->error('', '当前团长不存在'));

        $member_model = new MemberModel();
        $member_info = $member_model->getMemberInfo([ [ 'member_id', '=', $token[ 'data' ][ 'member_id' ] ] ], 'balance_withdraw_apply, balance_withdraw,balance,balance_money');
        $info[ 'data' ][ 'balance_withdraw_apply' ] = $member_info[ 'data' ][ 'balance_withdraw_apply' ];
        $info[ 'data' ][ 'balance_withdraw' ] = $member_info[ 'data' ][ 'balance_withdraw' ];
        $info[ 'data' ][ 'balance' ] = $member_info[ 'data' ][ 'balance' ];
        $info[ 'data' ][ 'balance_money' ] = $member_info[ 'data' ][ 'balance_money' ];

        //总订单
        $order_model = new Order();
        //粉丝数
        $info[ 'data' ][ 'team_count' ] = $member_model->getMemberCount([ [ 'cl_id', '=', $info[ 'data' ][ 'cl_id' ] ] ]);

        //今日
        $today_start_time = strtotime(date('Y-m-d 00:00:00', time()));
        $today_end_time = time();
        $info[ 'data' ][ 'day_order_count' ] = $order_model->getOrderCount([
            [ 'cl_id', '=', $info[ 'data' ][ 'cl_id' ] ],
            [ 'order_status', '<>', -1 ],
            [ 'create_time', 'between', [ $today_start_time, $today_end_time ] ]
        ])[ 'data' ];

        //售后
        $info[ 'data' ][ 'refund_order_count' ] = $order_model->getRefundOrderCount([
            [ 'o.cl_id', '=', $info[ 'data' ][ 'cl_id' ] ],
            [ 'og.refund_status', 'not in', '0,3' ]
        ])[ 'data' ];

        return $this->response($info);
    }

    /**
     * 设置休息
     */
    public function setRestStatus()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $rest_status = $this->params[ 'rest_status' ] ?? '';

        $leader_model = new Leader();
        $res = $leader_model->setLeaderRest($this->site_id, $this->member_id, $rest_status, 'member_id');
        return $this->response($res);
    }

    /**
     * 团长基础配置
     * @return false|string
     */
    public function config()
    {
        $config_model = new CommunityConfig();
        $res = $config_model->getConfig($this->site_id);
        return $this->response($res);
    }

    /**
     * 团长注册协议配置
     * @return false|string
     */
    public function settledAgreement()
    {
        $config_model = new CommunityConfig();
        $res = $config_model->getSettledAgreement($this->site_id);
        return $this->response($res);
    }

    /**
     * 列表信息
     */
    public function leaderPage()
    {

        $latitude = isset($this->params[ 'latitude' ]) ? $this->params[ 'latitude' ] : null; // 纬度
        $longitude = isset($this->params[ 'longitude' ]) ? $this->params[ 'longitude' ] : null; // 经度

        $community_config = new CommunityConfig();
        $community_distance = $config = $community_config->getConfig($this->site_id)[ 'data' ][ 'value' ][ 'community_distance' ];

        $leader_model = new Leader();
        $condition = [
            [ 'site_id', "=", $this->site_id ],
            [ 'status', '=', 1 ],
            [ 'rest_status', '=', 0 ],
        ];

        $latlng = array (
            'lat' => $latitude,
            'lng' => $longitude,
        );
        $field = '*';
        $list_result = $leader_model->getLocationLeaderList($condition, $field, $latlng, $community_distance);

        $list = $list_result[ 'data' ];

        if (!empty($longitude) && !empty($latitude) && !empty($list)) {
            foreach ($list as $k => $item) {
                if ($item[ 'longitude' ] && $item[ 'latitude' ]) {
                    $distance = getDistance((float) $item[ 'longitude' ], (float) $item[ 'latitude' ], (float) $longitude, (float) $latitude);
                    $list[ $k ][ 'distance' ] = $distance / 1000;
                } else {
                    $list[ $k ][ 'distance' ] = 0;
                }
            }
            // 按距离就近排序
            array_multisort(array_column($list, 'distance'), SORT_ASC, $list);
        }

        $default_cl_id = 0;
        if (!empty($list)) {

            $token = $this->checkToken();
            if (!$token[ 'code' ] < 0) {
                $member_model = new MemberModel();
                $default_cl_id = $member_model->getMemberInfo([ 'member_id' => $token[ 'data' ][ 'member_id' ] ], 'cl_id')[ 'cl_id' ];
            }
        }
        return $this->response($this->success([ 'list' => $list, 'cl_id' => $default_cl_id ]));
    }

    /*
     * 配置信息
     */
    public function account()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);
        if (request()->isPost()) {
            $page = input('page', 0);
            $size = input('size', 0);
            $community = model('community_leader')->getInfo([ [ 'member_id', '=', $this->member_id ] ], 'cl_id');
            $model = new CommunityAccount();
            $condition = [ [ 'cl_id', '=', $community[ 'cl_id' ] ], [ 'site_id', '=', $this->site_id ] ];
            $result = $model->getCommunityAccountPageList($condition, $page, $size, 'create_time desc', '*');
            return $this->response($result);
        }
    }

    /**
     * 团长海报
     * @return \app\api\controller\false|string
     */
    public function poster()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $qrcode_param[ 'source_member' ] = $token[ 'data' ][ 'member_id' ];

        $poster = new Poster();
        $res = $poster->recommendQc($this->params[ 'app_type' ], $this->params[ 'page' ], $token[ 'data' ][ 'member_id' ], $this->site_id);

        return $this->response($res);
    }

    /**
     * 设置会员的默认社区
     */
    public function updateMemberCommunity()
    {

        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $cl_id = isset($this->params[ 'cl_id' ]) ? $this->params[ 'cl_id' ] : 0; // 社区id
        $source_member = isset($this->params[ 'source_member' ]) ? $this->params[ 'source_member' ] : 0; // 社区id

        if (!empty($source_member) && $cl_id == 0) {
            $leader_model = new Leader();
            $cl_id = $leader_model->getLeaderInfo([ [ 'member_id', '=', $source_member ], [ 'status', '=', 1 ] ], 'cl_id');
            $cl_id = !empty($cl_id) ? $cl_id[ 'data' ][ 'cl_id' ] : 0;
        }
        $member_model = new MemberModel();
        $res = $member_model->editMember([ 'cl_id' => $cl_id ], [ [ 'member_id', '=', $token[ 'data' ][ 'member_id' ] ] ]);
        $res[ 'data' ] = array ( 'cl_id' => $cl_id );
        return $this->response($res);
    }

    /**
     * 获取会员所属社区
     */
    public function getMemberCommunity()
    {

        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $latitude = isset($this->params[ 'latitude' ]) ? $this->params[ 'latitude' ] : null; // 纬度
        $longitude = isset($this->params[ 'longitude' ]) ? $this->params[ 'longitude' ] : null; // 经度

        $member_model = new MemberModel();
        $cl_id = $member_model->getMemberInfo([ [ 'member_id', '=', $token[ 'data' ][ 'member_id' ] ] ], 'cl_id');

        if (empty($cl_id[ 'data' ][ 'cl_id' ])) {
            return $this->response($this->error("", "当前会员无绑定团长!"));
        } else {

            $leader_model = new Leader();
            $leader_info = $leader_model->getLeaderInfo([ 'cl_id' => $cl_id[ 'data' ][ 'cl_id' ] ], '*');

            //粉丝数
            $leader_info[ 'data' ][ 'team_count' ] = $member_model->getMemberCount([ [ 'cl_id', '=', $leader_info[ 'data' ][ 'cl_id' ] ] ]);

            $distance = getDistance((float) $leader_info[ 'data' ][ 'longitude' ], (float) $leader_info[ 'data' ][ 'latitude' ], (float) $longitude, (float) $latitude);
            $leader_info[ 'data' ][ 'distance' ] = $distance / 1000;
            return $this->response($leader_info);
        }
    }
}
